package com.lms.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-05-07 07:07
 * @Description: ${Description}
 */
public class ServerSocketChannel01 {
    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 30, TimeUnit.SECONDS, new SynchronousQueue<>());

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));

        while (true) {
            System.out.println("等待连接。。。");
            SocketChannel socketChannel = serverSocketChannel.accept();
            executor.execute(() -> handler(socketChannel));
        }
    }

    public static void handler(SocketChannel socketChannel) {
        try {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            System.out.println(Thread.currentThread().getName() + " --->  等待客户端发送数据。。。");
            while (socketChannel.read(buffer) != -1) {
                System.out.println(Thread.currentThread().getName() +"  --->    "+new String(buffer.array()));
                buffer.clear();
            }
            System.out.println(Thread.currentThread().getName() + " --->  等待客户端发送完成。。。");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
